package com.example.weizix.base;

import android.content.Context;
import android.support.annotation.IdRes;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import org.greenrobot.greendao.annotation.Id;

import java.util.ArrayList;
import java.util.List;

public abstract class BaseRlAdapter<T> extends RecyclerView.Adapter<BaseRlAdapter.BaseViewHolder> {
    private final Context context;
    private final ArrayList<T> mList;

    public BaseRlAdapter(Context context, ArrayList<T> mList){
        this.context = context;
        this.mList = mList;
    }
    @NonNull
    @Override
    public BaseViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(getLayout(), parent, false);
        BaseViewHolder holder = new BaseViewHolder(view);
        return new BaseViewHolder(view);
    }

    protected abstract int getLayout();

    @Override
    public void onBindViewHolder(@NonNull BaseViewHolder holder, int position) {
        T t = mList.get(position);
        bindData(holder,t);
    }

    protected abstract void bindData(BaseViewHolder holder, T t);
    public void addData(List<T> list){
        if (list!=null&&list.size()>0){
            mList.addAll(list);
            notifyDataSetChanged();
        }
    }


    @Override
    public int getItemCount() {
        return mList.size();
    }

    public static class BaseViewHolder extends RecyclerView.ViewHolder {
        SparseArray<View> mViews=new SparseArray();
        public BaseViewHolder(View itemView) {
            super(itemView);
        }
        public View findVIew(@IdRes int id){
            View view = mViews.get(id);
            if (view==null){
                view=itemView.findViewById(id);
                mViews.append(id,view);
            }
            return view;
        }
        public void setText(@IdRes int id,String text){
            try {
                TextView view= (TextView) findVIew(id);
                view.setText(text);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
